package ltd.newbee.mall.service.impl;
import ltd.newbee.mall.dao.OrderGoodsReportMapper;
import ltd.newbee.mall.service.OrderGoodsReportService;
import ltd.newbee.mall.util.PageQueryUtil;
import ltd.newbee.mall.util.PageResult;
import ltd.newbee.mall.vo.GoodsOrderDetailVO;
import ltd.newbee.mall.vo.GoodsReportVO;
import ltd.newbee.mall.vo.GoodsSummaryTotalVO;
import ltd.newbee.mall.vo.GoodsSummaryVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

@Service
public class OrderGoodsReportServiceImpl implements OrderGoodsReportService {

    @Resource
    private OrderGoodsReportMapper orderGoodsReportMapper;

    @Override
    public GoodsReportVO getGoodsReport(PageQueryUtil pageUtil) {
        Map<String, Object> params = pageUtil;

        // 获取商品汇总数据（不分页的总数）
        List<GoodsSummaryVO> allGoodsList = orderGoodsReportMapper.selectGoodsSummary(params);

        // 计算分页数据
        int start = (Integer) params.get("start");
        int limit = (Integer) params.get("limit");
        int totalCount = allGoodsList.size();

        // 手动分页
        List<GoodsSummaryVO> pageList = new ArrayList<>();
        int end = Math.min(start + limit, totalCount);
        for (int i = start; i < end; i++) {
            pageList.add(allGoodsList.get(i));
        }

        // 计算当前页的汇总统计
        GoodsSummaryTotalVO summary = calculateSummary(pageList);

        // 构建返回结果
        GoodsReportVO report = new GoodsReportVO();
        report.setList(pageList);
        report.setSummary(summary);
        report.setTotalCount(totalCount);
        report.setCurrPage((Integer) params.get("page"));
        report.setPageSize(limit);
        report.setTotalPage((int) Math.ceil((double) totalCount / limit));

        return report;
    }

    @Override
    public PageResult getGoodsOrderDetails(PageQueryUtil pageUtil) {
        Map<String, Object> params = pageUtil;
        Long goodsId = (Long) params.get("goodsId");

        if (goodsId == null) {
            return new PageResult(new ArrayList<>(), 0,
                    (Integer) params.get("limit"), (Integer) params.get("page"));
        }

        // 获取总数
        int totalCount = orderGoodsReportMapper.selectGoodsOrderDetailsCount(params);

        // 获取分页数据
        List<GoodsOrderDetailVO> list = orderGoodsReportMapper.selectGoodsOrderDetails(params);

        return new PageResult(list, totalCount,
                (Integer) params.get("limit"), (Integer) params.get("page"));
    }

    @Override
    public void exportGoodsReport(HttpServletResponse response, String startTime, String endTime,
                                  String billStatus, String refundStatus) {
        try {
            // 构建查询参数（导出不分页）
            Map<String, Object> params = new HashMap<>();
            if (StringUtils.hasText(startTime)) {
                params.put("startTime", startTime);
            }
            if (StringUtils.hasText(endTime)) {
                params.put("endTime", endTime);
            }
            if (StringUtils.hasText(billStatus)) {
                params.put("billStatus", billStatus);
            }
            if (StringUtils.hasText(refundStatus)) {
                params.put("refundStatus", refundStatus);
            }

            // 获取所有数据
            List<GoodsSummaryVO> goodsList = orderGoodsReportMapper.selectGoodsSummary(params);

            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("商品汇总报表");

            // 创建标题行样式
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setBorderBottom(BorderStyle.THIN);

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"商品ID", "商品名称", "销售数量", "销售金额", "退款数量", "退款金额", "净销售额", "已开票数量", "未开票数量"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 填充数据
            int rowNum = 1;
            for (GoodsSummaryVO goods : goodsList) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(goods.getGoodsId());
                row.createCell(1).setCellValue(goods.getGoodsName());
                row.createCell(2).setCellValue(goods.getTotalSales());
                row.createCell(3).setCellValue(goods.getTotalAmount().doubleValue());
                row.createCell(4).setCellValue(goods.getRefundCount());
                row.createCell(5).setCellValue(goods.getRefundAmount().doubleValue());
                row.createCell(6).setCellValue(goods.getNetAmount().doubleValue());
                row.createCell(7).setCellValue(goods.getBilledCount());
                row.createCell(8).setCellValue(goods.getUnbilledCount());
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = "商品汇总报表_" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-Disposition", "attachment; filename=" +
                    new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));

            // 写入响应流
            workbook.write(response.getOutputStream());
            workbook.close();

        } catch (Exception e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }

    /**
     * 计算汇总统计
     */
    private GoodsSummaryTotalVO calculateSummary(List<GoodsSummaryVO> goodsList) {
        GoodsSummaryTotalVO summary = new GoodsSummaryTotalVO();

        for (GoodsSummaryVO goods : goodsList) {
            summary.setTotalSales(summary.getTotalSales() + goods.getTotalSales());
            summary.setTotalAmount(summary.getTotalAmount().add(goods.getTotalAmount()));
            summary.setTotalRefundAmount(summary.getTotalRefundAmount().add(goods.getRefundAmount()));
            summary.setNetAmount(summary.getNetAmount().add(goods.getNetAmount()));
            summary.setTotalBilledCount(summary.getTotalBilledCount() + goods.getBilledCount());
            summary.setTotalUnbilledCount(summary.getTotalUnbilledCount() + goods.getUnbilledCount());
        }

        return summary;
    }


    @Override
    public void exportGoodsOrderDetails(HttpServletResponse response, Long goodsId, String startTime, String endTime,
                                        String billStatus, String refundStatus,String goodsName) {
        try {
            // 构建查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("goodsId", goodsId);
            if (StringUtils.hasText(goodsName)) {
                params.put("goodsName", goodsName);
            }
            if (StringUtils.hasText(startTime)) {
                params.put("startTime", startTime);
            }
            if (StringUtils.hasText(endTime)) {
                params.put("endTime", endTime);
            }
            if (StringUtils.hasText(billStatus)) {
                params.put("billStatus", billStatus);
            }
            if (StringUtils.hasText(refundStatus)) {
                params.put("refundStatus", refundStatus);
            }

            // 获取所有订单明细数据（不分页）
            List<GoodsOrderDetailVO> orderDetails = orderGoodsReportMapper.selectGoodsOrderDetails(params);

            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("商品订单明细");

            // 创建日期格式
            CellStyle dateCellStyle = workbook.createCellStyle();
            CreationHelper createHelper = workbook.getCreationHelper();
            dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

            // 创建标题行样式
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"订单号", "下单时间", "购买数量", "单价", "金额", "订单状态", "开票状态", "退款状态", "退款原因"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 填充数据
            int rowNum = 1;
            for (GoodsOrderDetailVO order : orderDetails) {
                Row row = sheet.createRow(rowNum++);

                // 订单号
                row.createCell(0).setCellValue(order.getOrderNo());

                // 下单时间 - 使用日期格式
                Cell dateCell = row.createCell(1);
                if (order.getCreateTime() != null) {
                    dateCell.setCellValue(order.getCreateTime());
                    dateCell.setCellStyle(dateCellStyle);
                } else {
                    dateCell.setCellValue("");
                }

                // 购买数量
                row.createCell(2).setCellValue(order.getGoodsCount());

                // 单价
                row.createCell(3).setCellValue(order.getSellingPrice().doubleValue());

                // 金额
                row.createCell(4).setCellValue(order.getTotalPrice().doubleValue());

                // 订单状态
                row.createCell(5).setCellValue(getOrderStatusText(order.getOrderStatus()));

                // 开票状态
                row.createCell(6).setCellValue(getBillStatusText(order.getIsBill()));

                // 退款状态
                row.createCell(7).setCellValue(order.getRefundStatus());

                // 退款原因
                row.createCell(8).setCellValue(order.getRefundReason() != null ? order.getRefundReason() : "");
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = "商品订单明细_" + goodsId + "_" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-Disposition", "attachment; filename=" +
                    new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));

            // 写入响应流
            workbook.write(response.getOutputStream());
            workbook.close();

        } catch (Exception e) {
            throw new RuntimeException("导出商品订单明细Excel失败", e);
        }
    }

    // 辅助方法：获取订单状态文本
    private String getOrderStatusText(Byte orderStatus) {
        Map<Byte, String> statusMap = new HashMap<>();
        statusMap.put((byte)0, "待支付");
        statusMap.put((byte)1, "已支付");
        statusMap.put((byte)2, "配货完成");
        statusMap.put((byte)3, "出库成功");
        statusMap.put((byte)4, "交易成功");
        statusMap.put((byte)-1, "手动关闭");
        statusMap.put((byte)-2, "超时关闭");
        statusMap.put((byte)-3, "商家关闭");
        return statusMap.getOrDefault(orderStatus, "未知");
    }

    // 辅助方法：获取开票状态文本
    private String getBillStatusText(String isBill) {
        Map<String, String> billMap = new HashMap<>();
        billMap.put("1", "未开票");
        billMap.put("2", "申请中");
        billMap.put("3", "已同意");
        billMap.put("4", "已开票");
        return billMap.getOrDefault(isBill, "未知");
    }



}
